package com.cykj.admin.service.impl;

import com.cykj.admin.mapper.CompanyCheckMapper;
import com.cykj.admin.service.ICompanyCheckService;
import com.cykj.admin.util.LicenseUtil;
import com.cykj.admin.util.OcrBusinessLicenseUtils;
import com.cykj.admin.vo.CompanyCheckVO;
import com.cykj.admin.vo.CompanyVO;
import com.cykj.admin.vo.IndustryVO;
import com.cykj.common.dto.ResponseDTO;
import com.cykj.common.entity.CompanyCheckDO;
import com.cykj.common.entity.CompanyDO;
import com.cykj.common.entity.IndustryDO;
import com.cykj.common.entity.RegionDO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import dev.langchain4j.model.openai.OpenAiChatModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @BelongsProject: smart_recruit_backend
 * @BelongsPackage: com.cykj.admin.service.impl
 * @Author: 小小卢
 * @CreateTime: 2025-08-16 13:46
 * @Description: TODO
 * @Version: 1.0
 */
@Service
public class CompanyCheckServiceImpl implements ICompanyCheckService {
    @Autowired
    private CompanyCheckMapper companyCheckMapper;
    @Autowired // 确保正确注入
    private OcrBusinessLicenseUtils ocrUtils;
    @Value("${fileUrl}")
    private String httpPath;
    @Value("${localPath}")
    private String localPath;
    @Autowired
    private OpenAiChatModel openAiChatModel;

    /**
     * @Description: 查询待审核公司
     * @Param: [companyCheckVO]
     * @return: java.util.List<com.cykj.common.entity.CompanyCheckDO>
     */
    @Override
    public ResponseDTO selectCheckCompany(CompanyCheckVO companyCheckVO) {

        PageInfo<CompanyCheckDO> page;
        //开启分页
        PageHelper.startPage(companyCheckVO.getCurrentPage(), companyCheckVO.getPageSize());
        List<CompanyCheckDO> companyCheckList = companyCheckMapper.selectCheckCompany(companyCheckVO);
        for (CompanyCheckDO item : companyCheckList) {

            item.setLicenseUrl(replaceUrl(item.getLicenseUrl()));
            item.setCompanyIcon(replaceUrl(item.getCompanyIcon()));
            item.setHrProve(replaceUrl(item.getHrProve()));
        }
        page = new PageInfo<>(companyCheckList);
        if (page.getTotal() < page.getPageSize() && companyCheckList.size() == 0 && page.getTotal() > 0) {
            companyCheckVO.setCurrentPage(1);
            PageHelper.startPage(companyCheckVO.getCurrentPage(), companyCheckVO.getPageSize());
            List<CompanyCheckDO> companyCheckList2 = companyCheckMapper.selectCheckCompany(companyCheckVO);
            for (CompanyCheckDO item : companyCheckList2) {
                item.setLicenseUrl(replaceUrl(item.getLicenseUrl()));
                item.setCompanyIcon(replaceUrl(item.getCompanyIcon()));
                item.setHrProve(replaceUrl(item.getHrProve()));
            }
            page = new PageInfo<>(companyCheckList2);
        }
        return ResponseDTO.success(page);
    }



    /**
     * @Description: 审核公司资质
     * @Param: [companyCheckVO]
     * @return: com.cykj.common.dto.ResponseDTO
     */
    @Override
    public ResponseDTO checkCompany(CompanyVO companyVO) {
        Integer checkStatus = companyVO.getCheckStatus();
        if (checkStatus == 1) {
            String license = changeUrl(companyVO.getLicenseUrl());
            CompanyVO companyInfo = LicenseUtil.getCompanyInfo(license);
            if (companyInfo == null) {
                return ResponseDTO.error("请上传清晰的营业执照！");
            }
            //确认公司是否已经存在
            CompanyDO companyDO = checkCompanyExist(companyInfo.getEnterpriseCode());
            if (companyDO != null) {
                Integer i = companyCheckMapper.demoteHr(companyDO.getCompanyId());
                if (i == 0){
                    return ResponseDTO.error("主账号降级失败！");
                }
                Integer j = companyCheckMapper.upgradeHr(companyVO.getHrId());
                if (j == 0){
                    return ResponseDTO.error("子账号升级失败，请联系管理员！");
                }

            } else {
                companyInfo.setHrId(companyVO.getHrId());
                String establishTime = companyInfo.getEstablishTime();
                companyInfo.setEstablishTime(establishTime.replace("年", "-").replace("月", "-").replace("日", ""));
                if (companyInfo.getOutTime() != null) {
                    companyInfo.setOutTime(companyInfo.getOutTime().replace("年", "-").replace("月", "-").replace("日", ""));
                }
                companyInfo.setLicenseUrl(license);
                companyInfo.setCompanyIcon(changeUrl(companyVO.getCompanyIcon()));


                String answer = openAiChatModel.chat("告诉我" + companyInfo.getCompanyName() + "的经纬度,是什么行业,是什么性质的企业,公司规模的规模是多少，请根据以下模版回复我（不要换行使用逗号隔开）：companyLocation:(只回复经度和纬度，用%#&隔开),IndustryName:(只回复行业名，如金融、开发等),companyType:(只回复：如国企、外企、私企等)，companySize:(只回复:如0-20等");
                String[] answers = answer.split(",");
                String industryName;
                if (answers.length == 4) {
                    String[] companyLocations = answers[0].split(":");
                    companyInfo.setLocationInfo(companyLocations[1]);

                    String[] companyTypes = answers[2].split(":");
                    companyInfo.setCompanyType(companyTypes[1]);

                    String[] companySizes = answers[3].split(":");
                    companyInfo.setCompanySize(companySizes[1]);

                    String[] industryNames = answers[1].split(":");
                    industryName = industryNames[1];
                    IndustryDO industryDO = companyCheckMapper.selectIndustry(industryName);
                    if (industryDO == null) {
                        IndustryVO industryVO = new IndustryVO();
                        industryVO.setIndustryName(industryName);
                        Integer i = companyCheckMapper.insertIndustry(industryVO);
                        if (i > 1) {
                            companyInfo.setIndustryId(industryVO.getIndustryId());
                        }
                    } else {
                        companyInfo.setIndustryId(industryDO.getIndustryId());
                    }
                    String companyAddress = companyInfo.getCompanyAddress();
                    String[] split = companyAddress.split("市");

                    String[] cities = split[0].split("省");
                    String city;
                    if (cities.length > 1) {
                        city = cities[1];
                    } else {
                        city = cities[0];
                    }

                    RegionDO regionDO = companyCheckMapper.getRegionId(city);
                    companyInfo.setRegionId(regionDO.getRegionId());
                    System.out.println("成立时间：" + companyInfo.getEstablishTime());
                    Integer i = companyCheckMapper.insertCompany(companyInfo);
                    if (i == 0) {
                        return ResponseDTO.error("公司信息生成失败！");
                    }


                    Integer j = companyCheckMapper.updateHrInfo(companyInfo.getHrId(), companyInfo.getCompanyId());
                    if (j == 0) {
                        return ResponseDTO.error("人事数据更新失败！");
                    }
                } else {
                    return ResponseDTO.error("获取公司信息失败！");
                }
            }
        }

        int rows = companyCheckMapper.checkCompany(companyVO);
        if (rows > 0) {
            return ResponseDTO.success(rows);
        }
        return ResponseDTO.error("审核失败");
    }


    /**
     * @Description: 路径转换
     * @Param: [fileName]
     * @return: java.lang.String
     */
    private String changeUrl(String fileName) {
        String staticFile = fileName.replace(httpPath, localPath);
        return staticFile.replace("file:", "");
    }

    private String replaceUrl(String filePath) {
        String replace = localPath.replace("file:", "");
        return filePath.replace(replace, httpPath);
    }

    /**
     * @Description: 判断公司是否存在
     * @Param: [enterpriseCode]
     * @return: void
     */
    private CompanyDO checkCompanyExist(String enterpriseCode) {
        return companyCheckMapper.checkCompanyExist(enterpriseCode);
    }


}